import axios from "axios";
import ipConfig from '../../public/config/config'
const service = axios.create({
  
  baseURL:ipConfig.baseUrl,
  // process.env.NODE_ENV === 'development' 来判断是否开发环境
  timeout: 5000,
});

service.interceptors.request.use(
  (config) => {
    let token = localStorage.getItem("token");
    if (token) {
      config.headers.common["Authorization"] = token;
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject();
  }
);

service.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      return response.data;
    } else {
      Promise.reject();
    }
  },
  (error) => {
    console.log(error);
    // 为了迎合非常规返回值做出的操作
    if(error.response.data.code === '1404'){
        return error.response.data
    } else if(error.response.data.code === '1402'){
        return error.response.data
    } else {
        return error.response.data
        // return Promise.reject()
    }
    // return Promise.reject();
  }
);
// 通用下载方法
export function download(url, params, filename) {
  return service
    .post(url, params, { responseType: "blob" })
    .then((res) => {
      const content = res;
      const blob = new Blob([content]);
      if ("download" in document.createElement("a")) {
        const elink = document.createElement("a");
        elink.download = filename;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      } else {
        navigator.msSaveBlob(blob, filename);
      }
    })
  //   .catch(err => {
  //         console.log(err);
  //         // this.$message.error(err)
  //         this.$message({
  //           message: JSON.parse(err).message,
  //           type: "error",
  //         });
  // })
    .catch((err) => {
      console.log(err);
      this.$message.error('Internal Server Error!')
    });
}
export default service;
